import "../style/slider.css";

/**
 * @param { HTMLElement } sliderElement
 */
function initSlider(sliderElement) {
    sliderElement.position = 0;

    let interval = sliderElement.getAttribute("interval");
    if (interval) {
        try {
            interval = parseFloat(interval);
        } catch (e) {
            console.error(e)
        }
    } else {
        interval = 3000;
    }
    setInterval(() => {
        sliderElement.position++;
        if (sliderElement.position >= sliderElement.querySelectorAll(".slide").length) {
            sliderElement.position = 0;
        }
        updateSlider(sliderElement);
    }, interval);
}


/**
 * @param { HTMLElement } sliderElement
 */
function updateSlider(sliderElement) {
    sliderElement
        .querySelectorAll(".slide")
        .forEach((element, index) => {
            if (index === sliderElement.position) {
                element.classList.add("active")
                element.animate([
                    { opacity: 0 },
                    { opacity: 1 }
                ], { duration: 500, easing: "ease-in" });
            } else {
                element.classList.remove("active");
            }
        });
}

document
    .querySelectorAll(".slider")
    .forEach((element) => {
        initSlider(element);
    });

